package com.greenold.dashboard.service.impl;

import com.greenold.common.core.domain.entity.SysUser;
import com.greenold.common.core.domain.model.LoginUser;
import com.greenold.common.utils.SecurityUtils;
import com.greenold.common.utils.ServletUtils;
import com.greenold.dashboard.domain.vo.*;
import com.greenold.dashboard.mapper.DashboardMapper;
import com.greenold.dashboard.service.IDashboardService;
import com.greenold.framework.web.service.TokenService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author YueYang
 * Created on 2025/10/17 11:52
 * @version 1.0
 */
@Service
public class DashboardServiceImpl implements IDashboardService {

    private static final Logger log = LoggerFactory.getLogger(DashboardServiceImpl.class);

    @Autowired
    private DashboardMapper dashboardMapper;

    @Autowired
    private TokenService tokenService;

    /**
     * 获取前端工作台饼图数据
     *
     * @return 前端工作台饼图数据
     */
    @Override
    public List<TopPieVO> getTopPie() {
        List<TopPieVO> topPieVOList = new ArrayList<>();
        //查询老人数量
        //1. 先查询所有住院老人数量
        Long totalElder = dashboardMapper.selectTotalElder();
        //2. 再查询请假老人数量
        Long leaveElder = dashboardMapper.selectLeaveElder();
        //3. 计算其他老人数量
        Long otherElder = totalElder - leaveElder;
        //4. 封装数据
        List<TopPieDataVO> topPieDataVOList = new ArrayList<>();
        topPieDataVOList.add(new TopPieDataVO("外出中", leaveElder));
        topPieDataVOList.add(new TopPieDataVO("在院中", otherElder));
        topPieVOList.add(new TopPieVO("elderlyCount", "老人数量", "人", totalElder, topPieDataVOList));

        //查询床位数量
        //1.查询空闲床位数量
        Long freeBedNum = dashboardMapper.selectFreeBedNum();
        //2.查询占用床位数量
        Long occupiedBedNum = dashboardMapper.selectOccupiedBedNum();
        //3. 封装数据
        topPieDataVOList = new ArrayList<>();
        topPieDataVOList.add(new TopPieDataVO("空闲床位", freeBedNum));
        topPieDataVOList.add(new TopPieDataVO("占用床位", occupiedBedNum));
        topPieVOList.add(new TopPieVO("bedCount", "床位数量", "个", freeBedNum + occupiedBedNum, topPieDataVOList));

        //查询服务单数量
        //1. 查询所有已执行和护理项目外的服务单数量
        Long serviceNum = dashboardMapper.selectServiceNum();
        //2. 查询所有已执行和护理项目内的服务单数量
        Long serviceNumWithProject = dashboardMapper.selectServiceNumWithProject();
        //3. 封装数据
        topPieDataVOList = new ArrayList<>();
        topPieDataVOList.add(new TopPieDataVO("护理计划外", serviceNum));
        topPieDataVOList.add(new TopPieDataVO("护理计划内", serviceNumWithProject));
        topPieVOList.add(new TopPieVO("serviceCount", "服务单数量", "个", serviceNum + serviceNumWithProject, topPieDataVOList));


        //查询员工数量
        //1. 查询普通员工数量
        Long commonNum = dashboardMapper.selectCommonNum();
        //2. 查询管理人员数量
        Long managerNum = dashboardMapper.selectManagerNum();
        //3. 封装数据
        topPieDataVOList = new ArrayList<>();
        topPieDataVOList.add(new TopPieDataVO("普通员工", commonNum));
        topPieDataVOList.add(new TopPieDataVO("管理人员", managerNum));
        topPieVOList.add(new TopPieVO("employeeCount", "员工数量", "人", commonNum + managerNum, topPieDataVOList));


        //查询收入金额
        //1. 查询月度账单
        Long monthlyBill = dashboardMapper.selectMonthlyBill();
        //2. 查询服务费用
        Long serviceFee = dashboardMapper.selectServiceFee();
        //3. 封装数据
        topPieDataVOList = new ArrayList<>();
        topPieDataVOList.add(new TopPieDataVO("月度账单", monthlyBill));
        topPieDataVOList.add(new TopPieDataVO("服务费用", serviceFee));
        topPieVOList.add(new TopPieVO("incomeCount", "收入金额", "元", monthlyBill + serviceFee, topPieDataVOList));


        return topPieVOList;
    }

    /**
     * 获取当前登录用户的信息
     *
     * @return 当前登录用户的信息
     */
    @Override
    public Map<String, String> getUserinfo() {
        Map<String, String> userinfo = new HashMap<>();

        try {
            // 使用SecurityUtils获取当前登录用户信息
            LoginUser loginUser = SecurityUtils.getLoginUser();

            if (loginUser != null) {
                // 获取用户基本信息
                SysUser user = loginUser.getUser();

                // 封装用户基本信息
                if (user != null) {
                    userinfo.put("userId", loginUser.getUserId().toString());
                    userinfo.put("username", user.getUserName());
                    userinfo.put("nickName", user.getNickName());
                    userinfo.put("email", user.getEmail());
                    userinfo.put("phonenumber", user.getPhonenumber());
                    userinfo.put("sex", user.getSex());
                    userinfo.put("avatar", user.getAvatar());

                    // 部门信息
                    if (user.getDept() != null) {
                        userinfo.put("deptName", user.getDept().getDeptName());
                    }

                    // 角色信息
                    if (user.getRoles() != null && !user.getRoles().isEmpty()) {
                        userinfo.put("roles", user.getRoles().get(0).getRoleName());
                    }
                }

            } else {
                log.warn("未获取到当前登录用户信息");
                userinfo.put("error", "未获取到当前登录用户信息");
            }
        } catch (Exception e) {
            log.error("获取用户信息时发生异常: {}", e.getMessage(), e);
            userinfo.clear(); // 清空可能的部分数据
            userinfo.put("error", "获取用户信息失败: " + e.getMessage());
        }

        return userinfo;
    }

    /**
     * 获取当前登录用户的代办任务列表
     *
     * @return 当前登录用户的代办任务列表
     */
    @Override
    public List<TodoTaskVO> getTodoTask() {
        return dashboardMapper.selectTodoTask();
    }

    /**
     * 获取老人等级分布
     *
     * @return 老人等级分布
     */
    @Override
    public List<TopPieDataVO> getElderLevel() {
        return dashboardMapper.selectElderLevel();
    }

    /**
     * 获取老人年龄分布
     *
     * @return 老人年龄分布
     */
    @Override
    public List<ElderAgeVO> getElderAge() {
        return dashboardMapper.selectElderAge();
    }

    /**
     * 获取雷达图服务能力分布
     *
     * @return 服务能力分布
     */
    @Override
    public List<DataVO> getServiceAbility() {
        List<DataVO> list = dashboardMapper.selectServiceAbility();
        //获取订单表中的所有订单赋值为最大值。
        Long max = dashboardMapper.getOrderMax();
        //设置最大值
        list.forEach(item -> item.setMax(max));

        List<String> serviceNames = new ArrayList<>();
        Collections.addAll(serviceNames, "助餐", "助浴", "复健运动", "洗头", " 口部清洁");
        //判断list是否大于等于5，不足遍历
        if (list.size() < 5) {
            //填充list到5个数据，如果serviceNames中不含有list中的name，添加值直至5个数据。‘
            for (String name : serviceNames) {
                if (!list.stream().anyMatch(item -> item.getName().equals(name))) {
                    list.add(new DataVO(name, 0L, max));
                }
            }
        }
        return list;
    }
}
